import log from '../../helpers/logger';
import { CronJob } from 'cron';
import db from '../../lib/db';

export const crontab = async (req, res, next) => {
  //查询crontab表构造定时任务
  const crontabList = await db.crontab.findMany({
    where: {
      status: 1,
    },
  });
  if (!crontabList){

  }else{
    //遍历定时任务
    for (const crontab of crontabList) {
      const { id, name, task, cron } = crontab;
      //删除超过10分钟的验证码
      const job = new CronJob(
        '* */10 * * * *', // cronTime
        function () {
          console.log(id);
          //超过10分钟的验证码
          const nowTimestamp = Date.now();
          const date = new Date(nowTimestamp);
          const withTimezone = date.toISOString();
        const tenMinutesAgo = new Date(nowTimestamp - 10 * 60 * 1000).toISOString();
        console.log(tenMinutesAgo);
        //sms_log表查询created_at时间十分钟之内的验证码是否存在
        db.sms_log.deleteMany({
          where: {
            created_at: {
              lte: tenMinutesAgo,
            }
          }})
          console.log(name);
        }, // onTick
        null, // onComplete
        true, // start
        'Asia/Shanghai' // timeZone
      );
    }
  }
  
  next();
};
